﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using MobMentality.Map;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;

namespace MobMentality.Social.People
{
	class Inciter : Person
	{
		private Queue<PersonType> targets;
		Person currentTarget;
		int currentTime;
		int waitTime;

		public Inciter(GroupController group, Vector2 position, int waitTime, ContentManager content)
			: base(PersonType.Inciter, group, position, content, "PersonInciter")
		{
			this.targets = new Queue<PersonType>();
			this.currentTime = 0;
			this.waitTime = waitTime;

			health = 100;
			cooldown = 60;
			currentCooldown = 0;
		}

		public int CurrentTime
		{
			get
			{
				return CurrentTime;
			}
		}

		public int NumTargets
		{
			get
			{
				return targets.Count;
			}
		}

		public void AddConvertee(PersonType type)
		{
			if (health > 0)
			{
				targets.Enqueue(type);
			}
		}

		public Person Update(IMapNavigate navigationMap, Point groupTarget)
		{
			if (health > 0)
			{
				Point currentTile = navigationMap.GetTile(MapPosition);
				Point inciterTargetTile;

				if (currentTarget == null)
				{
					if (targets.Count > 0)
					{
						currentTarget = PeopleHolder.Instance.NearestUnconverted(MapPosition, targets.Dequeue());
					}
					else
					{
						currentTarget = null;
						inciterTargetTile = groupTarget;
					}
				}

				if (currentTarget != null)
				{
					inciterTargetTile = navigationMap.GetTile(currentTarget.MapPosition);
				}
				else
				{
					inciterTargetTile = groupTarget;
				}

				if (currentTile.X != inciterTargetTile.X || currentTile.Y != inciterTargetTile.Y)
				{
					Point nextTile = navigationMap.nextAStarTile(currentTile, inciterTargetTile, delegate(Point point1, Point point2) { return (point2.X - point1.X) + (point2.Y - point1.Y); });

					//-1,-1 if there is no such path
					if (nextTile.X != -1 && nextTile.Y != -1)
					{
						SetTargetLocation(navigationMap.GetMapPosition(nextTile, new Vector2(100, 100)));
					}
				}
				else
				{
					if (currentTarget != null && currentTarget.Team == Team.Unconverted)
					{
						if ((currentTarget.MapPosition - MapPosition).Length() < 50)
						{
							if (currentTime == waitTime)
							{
								Person newMember = currentTarget;
								currentTarget = null;
								currentTime = 0;
								return newMember;
							}
							else
							{
								currentTime++;
							}
						}
						else
						{
							currentTime = 0;
						}
					}
				}
			}

			return null;
		}

		public void clearConvertees()
		{
			targets.Clear();
			currentTarget = null;
		}
	}
}
